<template>
  <!-- 详情组件 -->
  <div>
    <el-dialog v-model="fileDialog" width="75vw" style='height:900px' append-to-body :close-on-click-modal="false"
      :before-close="visibleDialogClose">
      <template #header>
        <div class="title_box">
          <div class="title1">知识管理</div>
          <el-divider direction="vertical"></el-divider>
          <div class="title2">团队</div>
        </div>
      </template>

      <div class="file_detail_box" v-loading="pageLoading">
        <!-- 左边 -->
        <div class="left">
          <div class="title_name">
            <div class="title_name_one">
              <svg-icon icon-class="network-fill" />
              <span>文件名称</span>
            </div>
            <div class="title_name_two">
              <span>{{ fileInfoData.realName ? fileInfoData.realName : '' }}</span>
              <span>{{ fileInfoData.suffix ? '.' + fileInfoData.suffix : '' }}</span>
            </div>
            <!-- tabs -->
            <div class="tabsBox" v-if="fileDialog">
              <el-tabs ref="tabsBoxRefs" v-model="activeName" @tab-click="handleClick">
                <el-tab-pane v-if="fileDetailType == 'file'" label="历史版本" name="history">
                  <template #label>
                    <span>历史版本</span>
                    <svg-icon icon-class="history" />
                  </template>
                </el-tab-pane>

                <el-tab-pane name="downloads">
                  <template #label>
                    <svg-icon icon-class="downloads" />
                    <span>下载记录</span>
                  </template>
                </el-tab-pane>

                <el-tab-pane name="enjoy">
                  <template #label>
                    <svg-icon icon-class="enjoy1" />
                    <span>分享链接</span>
                  </template>
                </el-tab-pane>
                <el-tab-pane name="user">
                  <template #label>
                    <svg-icon icon-class="user" />
                    <span>成员管理</span>
                  </template>
                </el-tab-pane>
                <el-tab-pane v-if="fileDetailType == 'file'" name="look">
                  <template #label>
                    <svg-icon icon-class="view" />
                    <span>查看记录</span>
                  </template>
                </el-tab-pane>
                <el-tab-pane v-if="fileDetailType == 'file'" name="print">
                  <template #label>
                    <svg-icon icon-class="printer" />
                    <span>打印记录</span>
                  </template>
                </el-tab-pane>

                <div>
                  <component ref="fileDetailAllRefs" :is="ComponentMap[activeName]" :fileDetailInfo="fileInfoData"
                    @refreshEnjoyLinkClick="getApiFilesShareFile" @enjoyListCurrentChange="getApiFilesShareFile">
                  </component>
                </div>
              </el-tabs>
            </div>
          </div>

          <!-- 标签 -->
          <!-- <div>
            <div class="titleText">标签</div>
            <div class="labelBox">
              <div class="labelBox_tags">
                <el-tag :key="tag.id" v-for="tag in labelList">
                  {{ tag.labelName }}
                </el-tag>
              </div>
              <TagsList ref="tagsListRefs" :parentObj="fileInfoData" @refreshData="tagsList_refreshData"></TagsList>
            </div>
          </div> -->

          <!-- 描述 -->
          <div class="titleText">描述</div>
          <div v-if="isInputBox" class="describeBox" @click="InputBox_openClick">
            <span class="describeText">
              {{ fileInfoData.remarks ? fileInfoData.remarks : '无' }}
            </span>
          </div>
          <div v-else>
            <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="inputString"> </el-input>
            <div class="describeBox_btn create_box">
              <el-button @click="InputBox_cancelClick">取 消</el-button>
              <el-button type="primary" @click="InputBox_confirmClick">确 定</el-button>
            </div>
          </div>
        </div>

        <!-- 右边 -->
        <div class="right">
          <!-- 按钮及图片 -->
          <div class="thumbnailBox">
            <div class="thumbnailBox_title">
              <i class="el-icon-picture-outline"></i>
              <span>缩略图</span>
            </div>
            <div class="imgBox">
              <img v-if="fileInfoData.thumbnailUrl" :src="proxy.$yuUtils.changePageImgPath(fileInfoData.thumbnailUrl)"
                alt="" />
              <svg-icon v-else :icon-class="proxy.$yuUtils.selectSvgIcon(fileInfoData)"
                style="font-size: 40px"></svg-icon>
            </div>
            <!-- 下载和更多 -->
            <div class="thumbnailBox_btnBox">
              <el-button class="btnclass" :disabled="judgePermission('download')" @click="downloadFileFunc">
                <svg-icon icon-class="download" />
              </el-button>
              <!-- 更多 -->
              <MoreList ref="moreListRefs" :rowItem="fileInfoData" :isSlot="true" @moreHandleCommand="moreHandleCommand"
                @click="clickData(fileInfoData)" :roleData="myFIleRoleList">
                <el-button class="btnclass">更多<svg-icon icon-class="mores" /></el-button>
              </MoreList>
            </div>
          </div>

          <!-- 基本信息 -->
          <div class="essential_info">
            <div class="title_box">
              <svg-icon icon-class="info3"></svg-icon>
              <span>基本信息</span>
            </div>
            <div class="essential_content">
              <el-row class="titleText" :gutter="20">
                <el-col :span="6" class="title1">路径</el-col>
                <el-col :span="18" class="title2">{{ fileInfoData.path }}</el-col>
              </el-row>
              <el-row class="titleText" :gutter="20">
                <el-col :span="6" class="title1">文件大小</el-col>
                <!-- <el-col :span="18" class="title3">{{ fileInfoData.size | proxy?.filterSizeUnit }}</el-col> -->
                <el-col :span="18" class="title3"> {{ formatSize(fileInfoData.size) }}</el-col>
              </el-row>
              <el-row class="titleText" :gutter="20">
                <el-col :span="6" class="title1">创建时间</el-col>
                <el-col :span="18" class="title3">{{ fileInfoData.createTime }}</el-col>
              </el-row>
              <el-row class="titleText" :gutter="20">
                <el-col :span="6" class="title1">更新时间</el-col>
                <el-col :span="18" class="title3">{{ fileInfoData.updateTime }}</el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 标签 -->
    <div>
      <TagsInfo ref="TagsInfoRefs" @refreshData="apiFilesLabelRecordQuerySelect(fileInfoData)" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ApiPerfilesShare, ApiPerQuerySelect, ApiPerRemarks } from '@/api/personDoc/personDocApi'
import useUserStore from '@/store/modules/user'
import { useTeamRoleStore } from '@/store/modules/teamRole'
const { proxy } = getCurrentInstance() as any
const userStore = useUserStore()
const teamRoleStore = useTeamRoleStore()
const myFIleRoleList = ref([])
const route = useRoute()
import HistoryList from '@/views/teamKnowdge/fileInfo/history-list.vue' // 历史版本列表

const fileDetailAllRefs = ref(null)
const emit: any = defineEmits(['InfoMoreHandleCommand'])
import DownloadList from '@/views/teamKnowdge/fileInfo/download-list.vue' // 下载记录
const downloadListRefs = ref()

import EnjoyList from '@/views/teamKnowdge/fileInfo/enjoy-list.vue' // 分享链接
const enjoyListRefs = ref()

import MoreList from '@/views/teamKnowdge/fileInfo/more-list.vue' // 更多
import TagsInfo from '@/views/teamKnowdge/fileInfo/tags-info.vue' // 标签
import UserRole from '@/views/teamKnowdge/fileInfo/userRole.vue' // 用户角色
import LookFile from '@/views/teamKnowdge/fileInfo/lookFile.vue' // 查看文件
import PrintFile from '@/views/teamKnowdge/fileInfo/printFile.vue' // 打印文件


const TagsInfoRefs = ref()

const ComponentMap = ref({
  history: markRaw(HistoryList),
  downloads: markRaw(DownloadList),
  enjoy: markRaw(EnjoyList),
  user: markRaw(UserRole),
  look: markRaw(LookFile),
  print: markRaw(PrintFile),

})

const isOpenCreateLink = ref(false)
const fileInfoData = ref({
  realName: '',
  suffix: '',
  type: '',
  thumbnailUrl: '',
  path: '',
  size: '' as any,
  createTime: '',
  updateTime: '',
  id: '',
  remarks: '',
  libraryType: ''
})
const fileDialog = ref(false)
const pageLoading = ref(false)
const activeName = ref('history')
const fileDetailInfo = ref({
  thumbnailUrl: '',
  type: '',
  path: '',
  size: '' as any,
  createTime: '',
  updateTime: '',
  id: ''
})
const labelList = ref([])
const isInputBox = ref(true)
const inputString = ref('')
const fileDetailType = ref('')
const visibleDialogClose = () => {
  fileDialog.value = false
  activeName.value = 'history'
  InputBox_cancelClick() //关闭描述输入框
}

/**如果在页面上点击的是更多和右键的分享链接,直接切换到分享链接 */
const enjoyMoreAndRightClick = async (row) => {
  await getDetailInfo(row)
  activeName.value = 'enjoy'

  // Array.isArray(row) ? await getApiFilesShareFile(row[0].id) : await getApiFilesShareFile();
  // await enjoyListRefs.value.createEnjoyLinkClick();
}

const formatSize = (size: number) => {
  return proxy.$yuUtils.filterSizeUnit(size)
}
const clickData = async (row) => {
  let paramsString = {
    teamId: route.query.teamId,
    treeNodeIds: [row.id],
    userId: userStore.userId
  }
  let res: any = await teamRoleStore.getUserTeamFileRoleApi({
    params: paramsString
  })
  if (res && res.data && res.data.length > 0) {
    res.data.forEach((roleData) => {
      if (roleData.params) {
        try {
          // Parse the params and merge them into myFIleRoleList
          let parsedParams = JSON.parse(roleData.params)
          myFIleRoleList.value = myFIleRoleList.value.concat(parsedParams)
        } catch (e) {
          console.error('Error parsing params:', e)
        }
      }
    })

    // Optionally, remove duplicates if needed
    myFIleRoleList.value = Array.from(new Set(myFIleRoleList.value.map((item: any) => JSON.stringify(item)))).map((item: string) =>
      JSON.parse(item)
    )
  }
}

/**获取文件详细信息 */
const getDetailInfo = async (row: any) => {
  // console.log('🚀 ~ getDetailInfo ~ row:', row);
  fileDialog.value = true
  if (Array.isArray(row)) {
    row = row[0]
  }

  fileInfoData.value = row
  fileDetailType.value = row.type
  if (row.type == 'file') {
    nextTick(() => {
      apiFilesLabelRecordQuerySelect(row)
      fileDetailAllRefs.value.apiOnlineSelectFilesVersions(row)
    })
    fileDialog.value = true
  } else {
    //文件夹
    fileDetailInfo.value = row
    fileDialog.value = true
    activeName.value = 'downloads'
    nextTick(() => {
      fileDetailAllRefs.value.getList(fileDetailInfo)
    })
  }
  let paramsString = {
    teamId: route.query.teamId,
    userId: userStore.userId,
    treeNodeIds: [row.id]
  }
  await teamRoleStore.getUserTeamFileRoleApi({
    params: paramsString
  })

  // console.log(row, '获取文件详细信息');
}

/**获取全部标签 */
const apiFilesLabelRecordQuerySelect = (row) => {
  let oParam = {
    fileId: row.id,
    fileType: row.libraryType,
    labelType: 'user'
  }
  ApiPerQuerySelect(oParam).then((res) => {
    labelList.value = res.data
  })
}

const handleClick = (tab: any, event: any) => {
  activeName.value = tab.paneName

  //   //历史版本
  if (activeName.value == 'history' && fileInfoData.value.type == 'file') {
    nextTick(() => {
      fileDetailAllRefs.value.apiOnlineSelectFilesVersions(fileInfoData)
    })
  }
  //   //下载记录
  if (activeName.value == 'downloads') {
    nextTick(() => {
      fileDetailAllRefs.value.getList(fileInfoData)
    })
  }

  if (activeName.value == 'enjoy') {
    nextTick(() => {
      fileDetailAllRefs.value.ShareFile(fileInfoData)
    })
  }
  if (activeName.value == 'user') {
    nextTick(() => {
      fileDetailAllRefs.value.getTableList(fileInfoData.value)
    })
  }
  if (activeName.value == 'look' && fileInfoData.value.type == 'file') {
    nextTick(() => {
      fileDetailAllRefs.value.getList(fileInfoData.value)
    })
  }
  if (activeName.value == 'print' && fileInfoData.value.type == 'file') {
    nextTick(() => {
      fileDetailAllRefs.value.getList(fileInfoData.value)
    })
  }
}

/**查询分享链接 */
const getApiFilesShareFile = async (e) => {
  nextTick(async () => {
    enjoyListRefs.value.historyLoading = true
    let oParam = {
      fileId: e || fileDetailInfo.value.id,
      page: enjoyListRefs.value.currentPage1 - 1,
      size: 10,
      type: 'personal'
    }

    await ApiPerfilesShare(oParam).then((res) => {
      if (res.code == 200) {
        enjoyListRefs.value.historyLoading = false
        enjoyListRefs.value.EnjoyHistory = res
      }
    })
  })
}

/**创建连接 */
// type=1创建链接  or  type=2编辑链接
const createFilesShareLink = (val, type) => {
  if (type == 1) {
    //为1的时候是创建链接
  }

  if (type == 2) {
    //为2的时候是编辑链接}
  }
}

/**描述输入框取消 */
const InputBox_cancelClick = () => {
  isInputBox.value = true
  inputString.value = ''
}

/**权限控制 */
const judgePermission = (str) => {
  //   if (this.pageType == 'enterprise') {
  //     return !this.$yuUtils.documentsPermissionFunc([str], this.enterpriseMyRoleList);
  //   } else if (this.pageType == 'team') {
  //     return !this.$yuUtils.documentsPermissionFunc([str], this.myTeamFIleRoleList);
  //   } else {
  //     return false;
  //   }
}

/**下载 */
const downloadFileFunc = async () => {
  pageLoading.value = true
  await proxy?.$download.downloadFile([fileInfoData.value.id], fileInfoData.value.libraryType)
  pageLoading.value = false

  // if (fileDetailInfo.value.type != 'file') {
  //   pageLoading.value = true;
  //   await proxy.$YUdowmload.YUdownloadFolder([fileDetailInfo]);
  //   pageLoading.value = false;
  //   return;
  // }
  // ElMessage.success('正在创建,请稍后...');
  // proxy.$YUdowmload.YUdowmloadFiles([fileDetailInfo]);
}

/**选择标签-确定按钮之后刷新数据 */
const tagsList_refreshData = () => {
  apiFilesLabelRecordQuerySelect(fileInfoData.value)
}

/**打开描述输入框 */
const InputBox_openClick = () => {
  isInputBox.value = false
  inputString.value = fileInfoData.value.remarks ? fileInfoData.value.remarks : ''
}

/**描述输入框确定 */
const InputBox_confirmClick = async () => {
  let res
  try {
    let params = {
      id: fileInfoData.value.id,
      remarks: inputString.value
    }

    res = await ApiPerRemarks(params)

    fileInfoData.value.remarks = inputString.value
    InputBox_cancelClick()
    ElMessage.success('修改成功')
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

// 更多
const moreHandleCommand = (command, item) => {
  emit('InfoMoreHandleCommand', command, item)
}

defineExpose({
  //调用组件需要导出 v-model的变量
  fileDialog,
  getDetailInfo,
  getApiFilesShareFile
})
</script>

<style lang="scss" scoped>
.titleText {
  font-size: 14px;
  color: #5f6e8e;
  line-height: 22px;
  font-weight: 400;
  margin: 8px 0;
}

:deep(.el-dialog) {
  margin: 0 auto; //为什么这么写,这么写才生效,才不会出现弹窗滚动效果
  margin-top: 5vh !important;

}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

.file_detail_box {
  height: calc(100vh - 235px);
  //   height: calc(100vh - 150px);
  // overflow-y: auto;
  width: 100%;
  display: flex;

  .right {
    width: 400px;
    min-width: 400px;
    padding: 20px;
  }

  .left {
    width: calc(100% - 400px);
    overflow-x: auto;
    white-space: nowrap;
    border-right: 1px solid #e0e2e4;
    padding-right: 20px;
    padding-bottom: 20px;

    .title_name {
      margin-bottom: 5px;

      .title_name_one {
        display: flex;
        align-items: center;
        color: #9d9d9d;
        margin-bottom: 6px;
        font-size: 14px;

        span {
          margin-left: 8px;
        }
      }

      .title_name_two {
        margin-top: 8px;
        font-size: 18px;
        color: #3d3d3d;
      }
    }
  }
}

.title_box {
  font-size: 13px;
  display: flex;
  align-items: center;

  .title1 {
    color: #5f6e8e;
    font-size: 15px;
  }

  .title2 {
    background-color: #e5ecfa;
    color: #5f6e8e;
    padding: 4px 6px 2px;
    border-radius: 2px;
    font-weight: bold;
  }
}

.tabsBox {
  min-width: 500px;

  // max-height: 500px;
  // overflow: auto;
  :deep(.el-tabs__item.is-active) {
    color: #6698ff;
  }

  :deep(.el-tabs__item:hover) {
    color: #6698ff;
  }

  :deep(.el-tabs__active-bar) {
    background-color: #6698ff;
  }

  :deep(.el-tabs__item) {
    color: #9d9d9d;
  }
}

.create_box {
  :deep(.el-button--mini) {
    padding: 5px 10px;
  }

  :deep(.el-button--text) {
    padding: 9px 15px;
    color: #aaa;
  }

  :deep(.el-button--text:hover) {
    color: #6698ff;
  }

  :deep(.el-button--primary) {
    background-color: #6698ff;
    border-color: #6698ff;
  }

  :deep(.el-button--primary:focus) {
    box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  }

  :deep(.el-button--primary:hover) {
    box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  }
}

.labelBox {
  display: flex;
  align-content: center;
  flex-wrap: wrap;

  .labelBox_tags {
    display: flex;
    flex-wrap: wrap;
  }

  .el-tag {
    margin: 0 5px 10px;
  }
}

.describeBox {
  width: 100%;

  .describeText {
    color: #cacaca;
    cursor: pointer;
    white-space: pre-wrap;
  }
}

.describeBox_btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 5px;
}

.thumbnailBox {
  .thumbnailBox_title {
    color: #9d9d9d;
    font-size: 15px;
    margin-bottom: 8px;
  }

  .imgBox {
    width: 100%;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #e0e2e4;
    overflow: hidden;

    img {
      width: 100%;
    }
  }

  .thumbnailBox_btnBox {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;

    .btnclass {
      margin-left: 10px;

      &:hover {
        background-color: #6698ff;
        color: #fff;
        border-color: #6698ff;
      }
    }

    .btnclass.is-disabled:hover {
      color: #c0c4cc;
      cursor: not-allowed;
      background-image: none;
      background-color: #fff;
      border-color: #e6ebf5;
    }
  }
}

.essential_info {
  margin-top: 30px;

  .title_box {
    color: #9d9d9d;
    font-size: 15px;
    margin-bottom: 15px;

    span {
      margin-left: 5px;
    }
  }

  .essential_content {
    .titleText {
      font-size: 14px;
      color: #666;
    }

    .title2 {
      color: #999999;
    }

    .title3 {
      color: #3d3d3d;
    }
  }
}

.comment_box {
  margin-top: 30px;
  // overflow-y: scroll;
  // overflow-x: hidden;
  // height: 400px;
  height: calc(100% - 300px);

  // border: 1px solid red;
  .title_box {
    color: #9d9d9d;
    font-size: 15px;
    margin-bottom: 15px;

    span {
      margin-left: 5px;
    }
  }
}
</style>
